﻿namespace CSharpAllDemo.Base
{
    public abstract class Executor
    {
        public abstract bool IsConnected { get; protected set; }
        public abstract bool IsExecuting { get; protected set; }
        /// <summary>
        /// 无返回值执行
        /// </summary>
        /// <param name="command"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public abstract Task<bool> ExcuteAsync(string command, int timeout);
        /// <summary>
        /// 无返回值带参数执行
        /// </summary>
        /// <param name="command"></param>
        /// <param name="parameter"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public abstract Task<bool> ExcuteAsync(string command, double parameter, int timeout);
        public abstract Task<IEnumerable<string>> ExcuteReturnAsync(string command, int timeout);
        public abstract Task<IEnumerable<string>> ExcuteReturnAsync(string command, double parameter, int timeout);
        public abstract Task TryConnectAsync();
        public abstract Task DisConnectAsync();
    }
    public class CommandResponse
    {
        private static readonly string[] ERROR_WORDS = { "ERROR", "BAD", "INVALID" };
        public string Command { get; set; } = string.Empty;
        public IEnumerable<string> Response { get; set; }
        public static CommandResponse Build(string text)
        {
            var results = text.Split("\r\n").Where(line => !string.IsNullOrEmpty(line));
            if (!results.Any()) return null;
            foreach (var error in ERROR_WORDS)
            {
                foreach (var res in results)
                {
                    if (res.ToUpper().Contains(error))
                    {
                        return null;
                    }
                }
            }

            return new CommandResponse
            {
                Command = $"{results.First()}\r\n",
                Response = results.Skip(1)
            };
        }

    }
}
